
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>社区积分榜</title>
    <style>
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #7ed321;
            --background: #f5f7fa;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
        }

        body {
            background: var(--background);
            padding-top: 140px;
        }

        /* 搜索栏样式 */
       .search-bar {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            padding: 15px;
            display: flex;
            gap: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }

       .search-input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 16px;
            transition: all 0.3s;
        }

       .search-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.2);
        }

       .search-btn {
            padding: 12px 25px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            transition: transform 0.2s;
        }

       .search-btn:active {
            transform: scale(0.95);
        }

        /* 用户列表样式 */
       .user-list {
            padding: 0 15px;
            max-width: 600px;
            margin: 0 auto;
        }
       .panel-content {
            padding: 0 15px;
            max-width: 600px;
            margin: 10px auto;
        }
       .flex {
          display: flex;
        }
       .justify-content-between {
          justify-content: space-between;
        }

       .user-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s;
            cursor: pointer;
            justify-content: space-between;
            align-items: center;
        }

       .user-card:hover {
            transform: translateY(-2px);
        }

       .user-info {
            flex: 1;
            display: flex;
            justify-content: space-between;
            width: 100%;
        }

       .user-community {
            color: var(--primary-color);
            font-weight: bold;
            font-size: 14px;
        }

       .user-name {
            font-size: 18px;
            margin: 5px 0;
        }

       .user-score {
            color: var(--secondary-color);
            font-weight: bold;
            font-size: 20px;
        }

        /* 模态框样式 */
       .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
            z-index: 2000;
        }

       .modal-content {
            background: white;
            max-width: 500px;
            margin: 20px auto;
            border-radius: 15px;
            padding: 25px;
            max-height: 80vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
        }
       .top-title {
          text-align: center;
          margin: 20px 0 20px 0;
          font-size: 24px;
        }
       .sort {
          display: flex; 
          align-items: center;
          font-size: 22px;
          font-weight: bold;
        }
       .user-card:nth-child(1) .sort {
          color: gold;
          font-size: 30px;
        }
       .user-card:nth-child(2) .sort {
          color: silver;
          font-size: 30px;
        }
       .user-card:nth-child(3) .sort {
          color: #cd7f32;
          font-size: 30px;
        }

        /* 新增角色筛选样式 */
       .role-filter {
          position: fixed;
          top: 90px;
          left: 0;
          right: 0;
          background: rgba(255, 255, 255, 0.95);
          padding: 10px 15px;
          display: flex;
          gap: 15px;
          overflow-x: auto;
          z-index: 999;
        }

       .role-item {
            display: flex;
            align-items: center;
            gap: 5px;
            white-space: nowrap;
        }

       .role-item input {
            width: 16px;
            height: 16px;
            accent-color: var(--primary-color);
        }

        /* 新增加载提示 */
       .loading {
            text-align: center;
            padding: 20px;
            color: #666;
            display: none;
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

       .record-item {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        /* 响应式设计 */
        @media (max-width: 480px) {
           .search-bar {
                flex-direction: column;
            }

           .user-card {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            body {
                padding-top: 220px;
            }

           .role-filter {
              top: 180px;
            }
        }


    </style>
</head>
<body>
    <!-- 搜索栏 -->
    <div class="search-bar">
        <select id="villageGroupSelect" class="search-input">
            <option value="">所有村小组</option>
        </select>
        <input type="text" id="nameInput"  class="search-input" placeholder="搜索名称">
        <button class="search-btn">搜索</button>
          <!-- 新增角色筛选 -->
    <div class="role-filter">

    </div>
    </div>

    <div class="top-title">社区积分榜</div>

  

    <div class="panel-content flex justify-content-between">

        <div>总人数：<span id="total-people"></span></div>
        <div>总积分：<span id="total-score"></span></div>
        <div>平均分：<span id="average-score"></span></div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list">

    </div>
    <!-- 新增加载提示 -->
    <div class="loading">加载中...</div>

    <!-- 积分详情模态框 -->
    <div class="modal">
        <div class="modal-content">
            <h2 id="detail-title"></h2>
            <div id="detail-content"></div>
        </div>
    </div>

    <script>
        const baseUrl = 'https://ankang.532628.com/'
        // 所有村小组接口
        const userApi = baseUrl + 'api/index/index';
        // 角色筛选接口
        const  villageGroupApi= baseUrl + 'api/index/communityList';
        // 用户列表接口
        const  roleApi= baseUrl + 'api/index/roleList';

        // 用户详情接口
        const detailApi = baseUrl + 'api/index/detailList';

        let villageGroups = [];
        let roles = [];
        let users = [];
        let currentPage = 1;
        const pageSize = 10;
        let isLoading = false;

        // 获取所有村小组数据并填充下拉框
        async function fetchVillageGroups() {
            try {
                const response = await fetch(villageGroupApi);
                const result = await response.json();
                if (result.code === 0) {
                    villageGroups = result.data;
                    const select = document.getElementById('villageGroupSelect');
                    villageGroups.forEach(group => {
                        const option = document.createElement('option');
                        option.value = group.id;
                        option.textContent = group.name;
                        select.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('获取村小组数据失败:', error);
            }
        }

        // 获取角色数据并创建复选框
        async function fetchRoles() {
            try {
                const response = await fetch(roleApi);
                const result = await response.json();
                if (result.code === 0) {
                    roles = result.data;
                    const roleFilter = document.querySelector('.role-filter');
                    roles.forEach(role => {
                        const label = document.createElement('label');
                        label.classList.add('role-item');
                        const input = document.createElement('input');
                        input.type = 'checkbox';
                        input.value = role.id;
                        input.checked = false;
                        label.appendChild(input);
                        label.appendChild(document.createTextNode(role.name));
                        roleFilter.appendChild(label);
                        input.addEventListener('change', searchUsers);
                    });
                }
            } catch (error) {
                console.error('获取角色数据失败:', error);
            }
        }

        // 根据搜索条件请求用户数据
        async function searchUsers(v) {
              const selectedVillageGroup = document.getElementById('villageGroupSelect').value;
              const name = document.getElementById('nameInput').value;
              const selectedRoleIds = Array.from(document.querySelectorAll('.role-item input:checked')).map(checkbox => parseInt(checkbox.value));
              currentPage = v || 1;
              try {
                  let url = `${userApi}?page=${currentPage}&pageSize=${pageSize}`;
                  if (selectedVillageGroup) {
                      url += `&cid=${selectedVillageGroup}`;
                  }
                  if (name) {
                      url += `&name=${encodeURIComponent(name)}`;
                  }
                  if (selectedRoleIds.length > 0) {
                      url += `&role_id=${selectedRoleIds.join(',')}`;
                  }
                  const response = await fetch(url);
                  const result = await response.json();
                  if (result.code === 0) {
                      document.getElementById('total-people').textContent = result.data.total;
                      document.getElementById('total-score').textContent = result.data.points_sum;
                      document.getElementById('average-score').textContent = parseFloat(result.data.points_sum/result.data.total).toFixed(2);

                      users = result.data.list;
                      if(users.length > 0) {
                        renderUsers();
                      } else {
                        const userList = document.querySelector('.user-list');
                        userList.innerHTML = '';
                        const userCard = document.createElement('div');
                        userCard.classList.add('user-card');
                        userCard.textContent = '暂无数据';
                        userList.appendChild(userCard);
                      }
                  }
              } catch (error) {
                  console.error('获取用户数据失败:', error);
              }
          }

        // 渲染用户列表
        function renderUsers() {
            const userList = document.querySelector('.user-list');
            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            const currentUsers = users.slice(start, end);
            // userList.innerHTML = '';
            if (currentPage === 1) {
                userList.innerHTML = '';
            }
            currentUsers.forEach((user, index) => {
                const userCard = document.createElement('div');
                userCard.classList.add('user-card');
                userCard.dataset.id = user.id; // 存储用户 ID
                const userInfo = document.createElement('div');
                userInfo.classList.add('user-info');
                const community = villageGroups.find(group => group.id === user.cid);
                const role = roles.find(r => r.id === user.role_id);
                const communityText = document.createElement('div');
                communityText.classList.add('user-community');
                communityText.textContent = community? community.name +'·'+ (role? role.name : '未知角色') : '未知社区 · 未知角色';
                const nameText = document.createElement('div');
                nameText.classList.add('sort');
                nameText.textContent = index + 1;
                
                const sortText = document.createElement('div');
                sortText.classList.add('user-name');
                sortText.textContent = user.name;

                const scoreText = document.createElement('div');
                scoreText.classList.add('user-score');
                scoreText.textContent = user.points +'分';

                userInfo.appendChild(communityText);
                userInfo.appendChild(nameText);
                userCard.appendChild(userInfo);
                userCard.appendChild(sortText);
                userCard.appendChild(scoreText);
                userList.appendChild(userCard);
                // 为用户卡片添加点击事件监听器
                userCard.addEventListener('click', async () => {
                const userId = userCard.dataset.id;
                await showUserDetail(userId);
                });
            });

            // 显示/隐藏加载提示
            document.querySelector('.loading').style.display = end < users.length? 'block' : 'none';
        }

         // 修改事件监听（统一使用防抖处理）
         let searchTimer;
        function handleSearch() {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => {
                currentPage = 1;
                searchUsers();
            }, 300);
        }

        document.querySelector('.search-btn').addEventListener('click', handleSearch);
        document.querySelectorAll('.role-item input').forEach(checkbox => {
            checkbox.addEventListener('change', handleSearch);
        });
        // 显示用户详情模态框
        async function showUserDetail(userId) {
            try {
                const response = await fetch(`${detailApi}?user_id=${userId}`);
                const result = await response.json();
                if (result.code === 0) {
                    const detailData = result.data;
                    const modal = document.querySelector('.modal');
                    const title = document.getElementById('detail-title');
                    const content = document.getElementById('detail-content');

                    // 假设详情数据中有用户姓名，可根据实际情况修改
                    title.textContent = `用户 ${users.find(u => u.id === parseInt(userId)).name} 的详情`;

                    // 渲染详情数据，这里简单假设详情数据是数组，可根据实际情况修改
                    content.innerHTML = detailData.map(item => `
                        <div class="record-item">
                            <p>日期: ${item.updated_at}</p>
                            <p>事件: ${item.type_name}</p>
                            <p>积分: ${item.points}</p>
                        </div>
                    `).join('');

                    // 显示模态框
                    modal.style.display = 'block';
                }
            } catch (error) {
                console.error('获取用户详情数据失败:', error);
            }
        }

        // 滚动加载处理
        window.addEventListener('scroll', () => {
            const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
            if (scrollTop + clientHeight >= scrollHeight - 200 &&!isLoading && currentPage * pageSize < users.length) {

                isLoading = true;
                document.querySelector('.loading').style.display = 'block';
                currentPage++;
                setTimeout(() => {
                    searchUsers(currentPage)
                    isLoading = false;
                }, 800);
            }
        });
      
         // 关闭模态框的逻辑
        const modal = document.querySelector('.modal');
     

        // 点击模态框外部关闭模态框
        window.addEventListener('click', (event) => {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        });
        // 为搜索按钮添加点击事件监听器
        document.querySelector('.search-btn').addEventListener('click', searchUsers);
        // 初始化
        fetchVillageGroups();
        fetchRoles();
        searchUsers();
    </script>
</body>
</html>